package com.ruoyi.web.controller.contest;

import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.system.domain.ContestCollect;
import com.ruoyi.system.service.IContestCollectService;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.util.Arrays;
import java.util.Comparator;
/**
 * 参赛报名Controller
 *
 * @author suncf
 * @date 2024-03-31
 */
@RestController
@RequestMapping("/system/collect")
@CrossOrigin
public class ContestCollectController extends BaseController {
    @Autowired
    private IContestCollectService contestCollectService;
    @Value("${ruoyi.profile}")
    private String dirPath;

    /**
     * 查询参赛报名列表
     */
    @PreAuthorize("@ss.hasPermi('system:collect:list')")
    @GetMapping("/list")
    public TableDataInfo list(ContestCollect contestCollect)
    {
        startPage();
        List<ContestCollect> list = contestCollectService.queryList(contestCollect);
        return getDataTable(list);
    }

    /**
     * 导出参赛报名列表
     */
    @PreAuthorize("@ss.hasPermi('system:collect:export')")
    @Log(title = "参赛报名", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ContestCollect contestCollect)
    {
        List<ContestCollect> list = contestCollectService.queryList(contestCollect);
        ExcelUtil<ContestCollect> util = new ExcelUtil<ContestCollect>(ContestCollect.class);
        util.exportExcel(response, list, "参赛报名数据");
    }

    /**
     * 获取参赛报名详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:collect:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id)
    {
        return success(contestCollectService.getById(id));
    }

    /**
     * 新增参赛报名
     */
    @PreAuthorize("@ss.hasPermi('system:collect:add')")
    @Log(title = "参赛报名", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ContestCollect contestCollect)
    {
        return toAjax(contestCollectService.save(contestCollect));
    }

    /**
     * 修改参赛报名
     */
    @PreAuthorize("@ss.hasPermi('system:collect:edit')")
    @Log(title = "参赛报名", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ContestCollect contestCollect)
    {
        return toAjax(contestCollectService.updateById(contestCollect));
    }

    /**
     * 删除参赛报名
     */
    @PreAuthorize("@ss.hasPermi('system:collect:remove')")
    @Log(title = "参赛报名", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids)
    {
        return toAjax(contestCollectService.removeByIds(Arrays.asList(ids)));
    }

    @PostMapping("/chunk")
    public AjaxResult upLoadChunk(@RequestParam("chunk") MultipartFile chunk,
                                       @RequestParam("filename") String filename) {
        File folder = new File(dirPath);
        if (!folder.exists() && !folder.isDirectory())
            folder.mkdirs();
        String filePath = dirPath + File.separator + filename;

        try {
            File saveFile = new File(filePath);
            FileOutputStream fileOutputStream = new FileOutputStream(saveFile);
            fileOutputStream.write(chunk.getBytes());
            fileOutputStream.close();
            chunk.transferTo(saveFile);
            System.out.println(filename);
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success();
    }

    @GetMapping("/merge")
    public AjaxResult MergeChunk(@RequestParam("hash") String hash,
                                      @RequestParam("filename") String filename) {
        File chunkFileFolder = new File(dirPath);
        File mergeFile = new File(dirPath + File.separator + filename);
        File[] chunks = chunkFileFolder.listFiles();
        //排序
        assert chunks != null;
        File[] files = Arrays.stream(chunks)
                .filter(file -> file.getName().startsWith(hash))
                .sorted(Comparator.comparing(o -> Integer.valueOf(o.getName().split("\\.")[0].split("_")[1])))
                .toArray(File[]::new);

        try {
            RandomAccessFile randomAccessFileWriter = new RandomAccessFile(mergeFile, "rw");
            byte[] bytes = new byte[1024];
            for (File chunk : files) {
                RandomAccessFile randomAccessFileReader = new RandomAccessFile(chunk, "r");
                int len;
                while ((len = randomAccessFileReader.read(bytes)) != -1) {
                    randomAccessFileWriter.write(bytes, 0, len);
                }
                randomAccessFileReader.close();
            }
            randomAccessFileWriter.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(hash);
        return AjaxResult.success(mergeFile);
    }
}
